package org.example.bombermanserver.handler;

import org.example.bombermanserver.model.Message;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class JsonMessageDecoder extends MessageToMessageDecoder<ByteBuf> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        String json = msg.toString(StandardCharsets.UTF_8);
        System.out.println("解码器收到原始数据: " + json);
        try {
            Message message = objectMapper.readValue(json, Message.class);
            out.add(message);
        } catch (Exception e) {
            System.err.println("解码失败，内容: " + json);
            e.printStackTrace();
        }
    }
}
